// components/VForm/VFormItem/VFormItem.js
import Schema from 'async-validator';
Schema.warning = () => {}

Component({
  relations: {
    '../VForm': {
      type: 'parent',
      linked(target) {
        if (target) {
          // target.addItem(this);
        }
      }
    },
    '../../VInput/VInput': {
      type: 'child', // 关联的目标节点应为子节点
      linked(target) {
        // console.log('link child', target);
      }
    }
  },
  options: {
    multipleSlots: true
  },
  properties: {
    label: {
      type: String,
      value: ''
    },
    value: {
      type: String,
      optionalTypes: [Number],
      value: ''
    },
    rule: {
      type: Object,
      optionalTypes: [Array]
    },
    prop: String
  },

  /**
   * 组件的初始数据
   */
  data: {
    errMsg: ''
  },

  /**
   * 组件的方法列表
   */
  methods: {
    validate(value, cb) {
      const { prop, rule } = this.data;
      if (rule && prop) {
        const schema = new Schema({ [prop]: rule });
        return schema.validate({ [prop]: value }, { firstFields: true, suppressWarning: false }).then(() => {
          this.setData({
            errMsg: ''
          });
          if (cb) {
            cb(true);
          }
          this.triggerEvent('valid', true);
          return Promise.resolve(true)
        }).catch(({ errors }) => {
          this.setData({
            errMsg: errors[0].message
          });
          if (cb) {
            cb(false);
          }
          this.triggerEvent('valid', false);
          return Promise.reject(errors)
        })
      }
      return Promise.resolve();
    },
    _getAllLi: function(){
      // var nodes = this.getRelationNodes('../../VInput/VInput');
      // console.log('allInputs', nodes);
    }
  },
  ready() {
    this._getAllLi()
  }
})
